package org.springblade.third.service.impl;

import lombok.RequiredArgsConstructor;
import org.springblade.core.third.executor.ThirdExecutor;
import org.springblade.core.third.config.ThirdProperties;
import org.springblade.third.dto.ThirdRequest;
import org.springblade.third.dto.ThirdResponse;
import org.springblade.third.service.ThirdInvokeService;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ThirdInvokeServiceImpl implements ThirdInvokeService {

	private final ThirdExecutor thirdExecutor;
	private final ThirdProperties thirdProperties;

	@Override
	public ThirdResponse<Object> invoke(ThirdRequest request) {
		int attempts = Math.max(1, thirdProperties.getRetryMaxAttempts());
		long backoffMs = Math.max(0, thirdProperties.getRetryBackoffMs());
		int i = 0;
		while (true) {
			i++;
			try {
				return thirdExecutor.execute(request);
			} catch (RuntimeException ex) {
				if (!thirdProperties.isRetryEnabled() || i >= attempts) {
					throw ex;
				}
				try {
					Thread.sleep(backoffMs);
				} catch (InterruptedException ignored) {
					Thread.currentThread().interrupt();
				}
			}
		}
	}
}


